from common.models.project_gantt import ProjectGantt
from common.models.project_link import ProjectLink
from application import app, db
from flask import Blueprint, request, make_response, redirect
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
from dingtalk import SecretClient, model
import json, requests
from common.libs.DataHelper import getCurrentTime,getCurrentDate

##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式

project_page = Blueprint("project_page", __name__)


# @award_page.route("/createproject", methods=['GET', 'POST'])
# def createproject():
#     form = request.json.get('form')
#     b = request.json.get('b')
#     floatsum = request.json.get('floatsum')
#     floatnow = request.json.get('floatnow')
#     creater = request.json.get('creater')
#     user = request.json.get('user')
#     print(form)
#
#     try:
#         award = AwardProject()
#         award.user = user
#         award.name = form['name']
#         award.sn = form['sn']
#         award.prefund = form['prefund']
#         award.prefunddate = form['prefunddate']
#         award.fund = form['fund']
#         award.a = form['a']
#         award.b = b
#         award.k1 = form['k1']
#         award.k2 = form['k2']
#         award.k3 = form['k3']
#         award.floatraito = form['floatraito']
#         award.floatsum = floatsum
#         award.floatnow = floatnow
#         award.creater = creater
#         award.status = 0
#         award.updated_time = award.created_time = getCurrentTime()
#         db.session.add(award)
#         db.session.commit()
#         id = award.id
#     except Exception as e:
#         print(e)
#         return json.dumps({"msg": "项目基础资料信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
#     else:
#         return json.dumps({"msg": "项目基础资料录入成功", "code": 200, "id": id}, ensure_ascii=False)


# @award_page.route("/adddetail", methods=['GET', 'POST'])
# def adddetail():
#     form = request.json.get('form')
#     id = request.json.get('id')
#     user = request.json.get('user')
#     nowfund = request.json.get('nowfund')
#     afterfund = request.json.get('afterfund')
#     detailfund = request.json.get('detailfund')
#     print(request.json)
#     try:
#         award = AwardDetail()
#         award.projectid = id
#         award.name = user
#         award.role = form['role']
#         award.detailraito = form['detailraito']
#         award.nowfund = nowfund
#         award.afterfund = afterfund
#         award.detailfund = detailfund
#         db.session.add(award)
#         db.session.commit()
#     except Exception as e:
#         print(e)
#         return json.dumps({"msg": "信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
#     else:
#         user = User.query.filter_by(id=user).first()
#         name = user.name
#         return json.dumps(
#             {"msg": "录入成功", "code": 200, 'name': name, 'role': form['role'], 'detailraito': form['detailraito'],
#              'nowfund': nowfund, 'afterfund': afterfund, 'detailfund': detailfund}, ensure_ascii=False)


# @award_page.route("/editdetail", methods=['GET', 'POST'])
# def editdetail():
#     form = request.json.get('form')
#     nowfund = request.json.get('nowfund')
#     afterfund = request.json.get('afterfund')
#     detailfund = request.json.get('detailfund')
#     print(request.json)
#
#     try:
#         award = AwardDetail.query.filter_by(id=form['id']).first()
#         award.projectid = form['projectid']
#         # award.name = form['userid']
#         # award.role = form['role']
#         award.detailraito = form['detailraito']
#         award.nowfund = nowfund
#         award.afterfund = afterfund
#         award.detailfund = detailfund
#         db.session.commit()
#     except Exception as e:
#         print(e)
#         return json.dumps({"msg": "信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
#     else:
#         return json.dumps(
#             {"msg": "修改成功", "code": 200, 'name': form['name'], 'role': form['role'], 'detailraito': form['detailraito'],
#              'nowfund': nowfund, 'afterfund': afterfund, 'detailfund': detailfund}, ensure_ascii=False)


@project_page.route("/getproject", methods=['GET', 'POST'])
def getproject():

    project = ProjectGantt.query.filter_by(status=1).all()
    link=ProjectLink.query.all()

    projectlist = []
    for item in project:
        temp = dict(id=item.id, text=item.text, user=item.username.name, start_date=str(item.start_date),
                    duration=item.duration,progress=item.progress,parent=item.parent,color=item.color,bz=item.bz,row_height=item.row_height,bar_height=item.bar_height)
        projectlist.append(temp)

    linklist =[]
    for item in link:
        temp = dict(id=item.linkid, source=item.source, target=item.target,type=item.type)
        linklist.append(temp)


    return json.dumps({"data":projectlist,"links":linklist}, ensure_ascii=False)


@project_page.route('/updateproject', methods=['GET', 'POST'])
def updateproject():
    userid = request.json.get('userid')
    print(userid)
    newdata = request.json.get('form')
    poster=request.json.get('postid')

    project = ProjectGantt.query.filter_by(id=newdata['id']).first()

    project.text = newdata['text']
    project.start_date = newdata['start_date'][0:10]

    project.duration = newdata['duration']
    project.progress = newdata['progress']
    project.parent = newdata['parent']
    project.color = newdata['color']
    project.status = 1

    project.bz = newdata['bz']
    if userid != []:
        project.userid = userid

    project.updated_time = getCurrentTime()

    db.session.commit()

    return json.dumps("更新成功", ensure_ascii=False)


@project_page.route('/addproject', methods=['GET', 'POST'])
def addproject():
    userid = request.json.get('userid')
    newdata = request.json.get('form')
    poster=request.json.get('postid')
    print(newdata)

    project = ProjectGantt()

    project.text = newdata['text']
    project.start_date = newdata['start_date'][0:10]

    if 'duration' in newdata:
        project.duration = newdata['duration']
    else:
        project.duration = 30
    if 'progress' in newdata:
        project.progress = newdata['progress']
    else:
        project.progress =0
    if 'color' in newdata:
        project.color = newdata['color']
    else:
        project.color = "#FF0000"
    project.parent = newdata['parent']
    if 'bz' in newdata:
        project.bz = newdata['bz']
    else:
        project.bz = ""
    project.bz = newdata['bz']
    project.row_height=newdata['row_height']
    project.bar_height=newdata['bar_height']
    project.status = 1
    if userid != []:
        project.userid = userid

    project.created_time = getCurrentTime()


    db.session.add(project)
    db.session.flush()
    db.session.commit()
    id = project.id

    return json.dumps({"id":id,"messages":"新建成功"}, ensure_ascii=False)


@project_page.route('/deleteproject', methods=['GET', 'POST'])
def deleteproject():
    id = request.json.get('id')

    project = ProjectGantt.query.filter_by(id=id).first()
    project.status = 0
    project.updated_time = getCurrentTime()
    db.session.commit()

    return json.dumps("删除成功", ensure_ascii=False)


@project_page.route('/addlink', methods=['GET', 'POST'])
def addlink():
    id=request.json.get('id')
    source = request.json.get('source')
    target = request.json.get('target')
    type = request.json.get('type')


    link = ProjectLink()

    link.linkid=id
    link.source = source
    link.target = target
    link.type = type

    db.session.add(link)
    # db.session.flush()
    db.session.commit()
    # id = link.id

    return json.dumps({"messages": "新建成功"}, ensure_ascii=False)

@project_page.route('/deletelink', methods=['GET', 'POST'])
def deletelink():
    id = request.json.get('id')
    print(id)
    link = ProjectLink.query.filter_by(linkid=id).delete()
    db.session.commit()

    return json.dumps({"messages": "删除成功"}, ensure_ascii=False)